package com.sugon.shiro;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.cait.service.ResCenterClient;
import com.cait.service.rescenter.ResultMessage;
import com.cait.service.rescenter.UserInfo;
import com.sugon.cache.J2CacheUtils;
import com.sugon.dao.SysMenuDao;
import com.sugon.dao.SysUserDao;
import com.sugon.dao.SysUserRoleDao;
import com.sugon.entity.SysMenuEntity;
import com.sugon.entity.SysUserEntity;
import com.sugon.modules.sys.service.IResCenterAuthenticator;
import com.sugon.modules.sys.service.IUserManager;
import com.sugon.service.SysConfigService;
import com.sugon.utils.Constant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.rmi.RemoteException;
import java.util.*;

/**
 * 认证
 *
 * @author lipengjun
 * @date 2017年11月19日 上午9:49:19
 **/
@Slf4j
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private SysUserDao sysUserDao;
    @Resource
    private SysUserRoleDao sysUserRoleDao;
    @Autowired
    private SysMenuDao sysMenuDao;
    @Autowired
    private SysConfigService configService;
    @Autowired
    private IResCenterAuthenticator resCenterAuthenticator;
    @Autowired
    private IUserManager userManager;

    @Override
    public Class getAuthenticationTokenClass() {
        return super.getAuthenticationTokenClass();
    }

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SysUserEntity user = (SysUserEntity) principals.getPrimaryPrincipal();
        String userId = user.getUserId();

        List<String> permsList = (List<String>) J2CacheUtils.get(Constant.PERMS_LIST + userId);

        if (permsList == null) {
            permsList = refreshRedis(user);
        }

        //用户权限列表
        Set<String> permsSet = new HashSet<>();
        if (permsList != null && permsList.size() != 0) {
            for (String perms : permsList) {
                if (StringUtils.isBlank(perms)) {
                    continue;
                }
                permsSet.addAll(Arrays.asList(perms.trim().split(",")));
            }
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permsSet);
        // 设置用户角色
        Set<String> roleCodeList = sysUserRoleDao.queryRoleCodeList(userId);
        if(CollectionUtil.isNotEmpty(roleCodeList)){
            info.setRoles(roleCodeList);
        }
        return info;
    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        String password = new String((char[]) token.getCredentials());

        /*
            登录方式有两种：
                单点登录验证和登录页面登录验证，两种方式都需要校验
                单点登录验证：不需要验证密码
                登录页面登录验证：
                    校验登陆用户是否为特殊人员(即不属于任何部门的用户)
                            如果是，采用用户名/密码认证
                            如果不是，则走OA身份认证
         */
        // 校验账户是否存在
        SysUserEntity user = sysUserDao.queryByUserName(username);
        if (user == null) {
            throw new UnknownAccountException(StrUtil.format("工号为[{}]的员工非当前系统用户，不能使用该系统！", username));
        }
        // 根据系统设置的认证flag来决定是否认证
        String isAuthFlag = configService.getIsAuth();
        if (Constant.AUTH.equals(isAuthFlag)) {
            if (StrUtil.isNotEmpty(password)) {
                if (StrUtil.isEmpty(user.getDeptId())) {
                    if (!password.equals(user.getPassWord())) {
                        throw new IncorrectCredentialsException(StrUtil.format("账号{}或密码{}不正确，比对方式：{}", username, password, "密码比对"));
                    }
                } else {
                    // 进行长安中心统一认证
                    ResultMessage resultMessage = resCenterAuthenticator.doResCenterAuthenticate(username, password);
                    boolean authResult = resultMessage != null && resultMessage.isIsSuccess();
                    if (!authResult) {
                        throw new IncorrectCredentialsException(StrUtil.format("账号{}或密码{}不正确，比对方式：{}", username, password, "统一认证"));
                    }
                    // 如果到这里说明已经认证成功，那么需要更新erms中的unionId，
                    String identityToken = resultMessage.getMsg();
                    if (StrUtil.isNotEmpty(identityToken)) {
                        try {
                            UserInfo userInfo = ResCenterClient.getResCenterApi().getUserByToken(identityToken);
                            if (userInfo != null) {
                                user.setUnionId(userInfo.getUserId());
                                sysUserDao.updateUnionId(user.getUserId(), userInfo.getUserId());
                            }
                        } catch (RemoteException e) {
                            log.error("远程调用长安认证中心获取用户身份信息异常", e);
                        }
                    }
                }
            }
        }

        // 校验账户是否锁定
        if (user.getStatus() == 0) {
            throw new LockedAccountException(StrUtil.format("账号[{}]已被锁定,请联系管理员", user.getUserName()));
        }
        // 执行登录初始化
        userManager.loginSuccessInit(null, user.getUserId());

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
        return info;
    }

    private List<String> refreshRedis(SysUserEntity user) {
        List<String> permsList;

        //系统管理员，拥有最高权限
        if (Constant.SUPER_ADMIN.equals(user.getUserId())) {
            List<SysMenuEntity> menuList = sysMenuDao.queryList(new HashMap<String, Object>());
            permsList = new ArrayList<>(menuList.size());
            for (SysMenuEntity menu : menuList) {
                permsList.add(menu.getPerms());
            }
        } else {
            permsList = sysUserDao.queryAllPerms(user.getUserId());
        }
        J2CacheUtils.put(Constant.PERMS_LIST + user.getUserId(), permsList);

        return permsList;
    }

}
